package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsForm;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.FinishedGoodsHelper;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * User: Murali Krishna Yengala
 * Date: May 28, 2005
 * Time: 4:43:49 PM
 */
public class FinishedGoodsCommand extends ChipTrackExtendedAction{
    
    public ActionForward executeRequest( ActionMapping mapping,
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception
    {
        FinishedGoodsForm finishedGoodsForm = (FinishedGoodsForm) form;
        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        int baseProductId = -1;
        try
        {
            String baseProductIdS = finishedGoodsForm.getBaseProductId();
            baseProductIdS = baseProductIdS == null ? "" : baseProductIdS.trim();
            baseProductId = Integer.parseInt( baseProductIdS);
        }
        catch( NumberFormatException e)
        {}

        ArrayList baseProductsList = new ArrayList();
        ArrayList customersList = new ArrayList();
        try
        {
            baseProductsList = FinishedGoodsDAO.getBaseProducts();
        }
        catch( ScalarException e)
        {
            e.printStackTrace();
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
        }
        try
        {
            customersList = FinishedGoodsDAO.getAllCustomers();
        }
        catch( ScalarException e)
        {
            e.printStackTrace();
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "");
        }
        request.removeAttribute("fgiProductsList");
        FinishedGoodsHelper.setFgiProducts( baseProductId, request, errors, info);
        request.setAttribute("baseProductsList", baseProductsList);
        request.setAttribute("customersList", customersList);
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        return mapping.findForward( "new" );
    }
}
